<?php
namespace control;
/*
*成本核算类
*/

class costCountClass extends adIndexClass
{
    private const page = 'costCount';
    private const title = '成本核算';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => "单据日期",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'lineName'         => [
                        'name'  => '生产线',
                        'width' => 150,
                    ],
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '产品名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'num'          => [
                        'name'  => '实际产量',
                        'width' => 100,
                    ],
                    'materialFee'          => [
                        'name'  => '材料耗用(' . static::$unit . ')',
                        'width' => 100,
                    ],
                    'peopleFee'          => [
                        'name'  => '工人计件(' . static::$unit . ')',
                        'width' => 100,
                    ],
                    'money'          => [
                        'name'  => '分摊费用(' . static::$unit . ')',
                        'width' => 100,
                    ],
                    'costTotal'          => [
                        'name'  => '成本合计(' . static::$unit . ')',
                        'width' => 100,
                    ],
                    'costPrice'          => [
                        'name'  => '成本单价(' . static::$unit . ')',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(array("name" => "orderNo")),
                    '生产线'  => selectMultiple(array("name" => "lineId", "table" => "product_line",'where'=>"coid = '".self::$coid."'",   'sqlField' => 'name', 'field' => "concat(workshop,'-',name) as name,id", 'sqlId' => 'id', 'class' => 'width200')),
                    "产品编码" => text(array("name" => "code")),
                ],
                [
                    "产品名称" => text(array("name" => "materialName")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }



    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            'a.orderNo' => $this->post('orderNo'),
            'c.name' => $this->post('materialName'),
            'c.code' => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid" => self::$coid,
            "a.state" => '已确认',
            "a.lineId" => $this->post('lineId'),
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'a.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.recordDate desc,a.time',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "machining_order as a join machining_order_mx as mx on a.id = mx.orderId join product_line as b on a.lineId = b.id join material as c on c.id = mx.materialId",
            "where" => $where,
            'field' => "a.*,mx.id as mxId,mx.unit,b.workshop,b.name as lineName,c.code,c.name as materialName,c.model",
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid . self::page . 'Sql', $page['fullSql']);
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['mxId']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['mxId'] . "')"),
            );
            $result = $this->inFee($array['mxId']);
            $peopleFee = $this->peopleFee($array['mxId']);
            $materialFee = $this->materialFee($array['mxId']);
            $costTotal = $peopleFee + $materialFee + $result['money'];

            $liButton[] = $this->dominate($dominate);
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'num':
                        $row[] = self::lostZero($result['num'],'numPrecision');
                        break;
                    case 'materialFee':
                        $row[] = $materialFee;
                        break;
                    case 'peopleFee':
                        $row[] = $peopleFee;
                        break;
                    case 'money':
                        $row[] = $result['money'];
                        break;
                    case 'costTotal':
                        $row[] = $costTotal;
                        break;
                    case 'costPrice':
                        $row[] = $result['num'] > 0 ? self::formattingFigure($costTotal / $result['num']) : 0;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $inventory = find(array(
            'table'  => ' machining_order as a join machining_order_mx as mx on a.id = mx.orderId join material as c on c.id = mx.materialId join machining_in_order_detail as miod on miod.sourceId = mx.id join inventory_detail as inventory on inventory.sourceId = miod.id ',
            'single'=>$where,
            'field'=>"ifnull(SUM((CASE WHEN inventory.unit = c.unit_one THEN inventory.num*c.unit_one_num WHEN inventory.unit = c.unit_two THEN inventory.num*c.unit_two_num ELSE inventory.num END)/(CASE WHEN mx.unit = c.unit_one THEN c.unit_one_num WHEN mx.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $money = find(array('table' => 'cost_allocation_price', 'where' => "machiningOrderMxId in (select mx.id from machining_order as a join machining_order_mx as mx on a.id = mx.orderId join product_line as b on a.lineId = b.id join material as c on c.id = mx.materialId where 1=1 {$where})", 'sum' => 'money'));
        $total    = [
            'num'        => self::lostZero($inventory['num'],'num'),
            'money'        => self::lostZero($money),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $machiningOrderMx = query('machining_order_mx', " id = '{$this->get('id')}'");
        if (empty($machiningOrderMx['id'])) {
            $html = '未找到此生产订单';
        } else {
            //菜单
            $data = array(
                "id" => $machiningOrderMx['id'],
            );
            //生成表单
            $data['html'] = "";
            $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
            /****报工******/
            $reportTr[] = ['单据日期', '单据编号', '生产线', '物料编码', '物料名称', '规格型号', '单位', '仓库', '数量', '金额(' . static::$unit . '）'];
            $result = find(array(
                'table' => "machining_in_order as a join machining_in_order_detail as b on a.id = b.orderId",
                'field' => "b.*",
                'where' => "b.sourceId = '$machiningOrderMx[id]' and a.state = '已确认' order by b.list"
            ));
            $reportTotal = ['num'=>0,'money'=>0];
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $product_line = query('product_line', " id = '$machiningOrder[lineId]'");
                $warehouse = query('warehouse', "id = '$array[warehouseId]'");
                $num = 0;
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[id]' and num >0 and coid = '" . self::$coid . "'"));
                foreach ($inventoryAll['array'] as $item) {
                    $num += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                }
                $price = inventoryDefaultClass::getInventoryPrice($array['materialId'], $array['unit']);
                $reportTr[] = [
                    $machiningOrder['recordDate'],
                    $machiningOrder['orderNo'],
                    $product_line['workshop'] . '-' . $product_line['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $warehouse['name'],
                    self::lostZero($num,'numPrecision'),
                    self::lostZero($price * $num),
                ];
                $reportTotal['num'] += $num;
                $reportTotal['money'] += $price * $num;
            }
            $total_tr = [
                8 => self::lostZero($reportTotal['num'], 'numPrecision'),
                9 => self::lostZero($reportTotal['money']),
            ];
            $data['html'] .= $this->detailList([
                'title' => '报工数据',
                'html' => $this->listTable(array('tr' => $reportTr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            $machiningOrderObj = new machiningOrderClass();
            /****领料明细（领料单-退料单）******/
            $materialTr[] = ['存货类别', '物料编码', '物料名称', '规格型号', '单位', '额定数量', '损耗率(%)', '计划用量', '实际BOM用量', '实际领料', '实际退料', '实际用量','成本', '备注'];
            $all = find(array(
                'table' => "pick_order as a join pick_order_detail as b on a.id = b.orderId",
                'field' => "b.*,a.recordDate",
                'where' => "a.state = '已确认' and a.type=0 and b.sourceId in (select id from machining_order_detail where orderId = '$machiningOrder[id]' and targetSkuId = '$machiningOrderMx[id]' and state = '已确认')"
            ));
            $materialTotal = ['num'=>0,'quantity'=>0,'bom'=>0,'pick'=>0,'return'=>0,'used'=>0,'cost'=>0];
            foreach ($all['array'] as $array) {
                $machiningOrderDetail = query('machining_order_detail', "id = '$array[sourceId]'");
                $material = query('material', " id = '$array[materialId]'");

                $pickNum = 0;
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[id]' and num >0 and coid = '" . self::$coid . "'"));
                foreach ($inventoryAll['array'] as $item) {
                    $pickNum += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                }

                //退料数量
                $returnNum = 0;
                $returnAll = find(array(
                    'table' => "pick_order as a join pick_order_detail as b on a.id = b.orderId",
                    'field' => "b.*",
                    'where' => "a.state = '已确认' and a.type=1 and
                 b.sourceId in (select d.id from pick_order as c join pick_order_detail as d on c.id = d.orderId where d.materialId = '$array[materialId]' and c.state = '已确认' and c.type = 0 and d.sourceId in (select id from machining_order_detail where orderId = '$machiningOrder[id]' and targetSkuId = '$machiningOrderMx[id]' and state = '已确认')) "
                ));
                foreach ($returnAll['array'] as $returnMaterail) {
                    $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[id]' and num >0 and coid = '" . self::$coid . "'"));
                    foreach ($inventoryAll['array'] as $item) {
                        $returnNum += machiningOrderClass::material_num_change($returnMaterail['materialId'], $item['unit'], $array['unit'], $item['num']);
                    }
                }
                $price = inventoryDefaultClass::getInventoryPrice($array['materialId'], $array['unit'], $array['recordDate']);//库存均价
                $bomArray = $machiningOrderObj->getFactMaterialNum($machiningOrderDetail['orderId']);
                $bomNum = $machiningOrderObj->getMaterialBom($bomArray, $array['sourceId'], $array['materialId']);
                $materialTotal['num'] += $machiningOrderDetail['num'];
                $materialTotal['quantity'] += $machiningOrderDetail['quantity'];
                $materialTotal['bom'] += $bomNum;
                $materialTotal['pick'] += $pickNum;
                $materialTotal['return'] += $returnNum;
                $materialTotal['used'] += $pickNum - $returnNum;
                $materialTotal['cost'] += $price*($pickNum - $returnNum);
                $materialTr[] = [
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($machiningOrderDetail['num'],'num'),
                    ($machiningOrderDetail['loss'] * 100) . '%',
                    self::lostZero($machiningOrderDetail['quantity'],'num'),
                    self::lostZero($bomNum,'num'),
                    $pickNum,
                    $returnNum,
                    $pickNum - $returnNum,
                    self::formattingFigure($price*($pickNum - $returnNum)),
                    $array['text'],
                ];
            }
            $total_tr = [
                5 => self::lostZero($materialTotal['num'], 'num'),
                7 => self::lostZero($materialTotal['quantity'], 'num'),
                8 => self::lostZero($materialTotal['bom'], 'num'),
                9 => self::lostZero($materialTotal['pick'], 'num'),
                10 => self::lostZero($materialTotal['return'], 'num'),
                11 => self::lostZero($materialTotal['used'], 'num'),
                12 => self::formattingFigure($materialTotal['cost']),
            ];
            $data['html'] .= $this->detailList([
                'title' => '领料明细',
                'html' => $this->listTable(array('tr' => $materialTr, 'showSort' => true, 'total' => $total_tr)),
            ]);

            //材料分配明细
            $disTr[] = ['存货类别', '物料编码', '物料名称', '规格型号', '单位', '实际BOM用量', '实际分配用量'];
            $all = find(array('table' => 'material_distribute_num', 'where' => "machiningOrderMxId = '$machiningOrderMx[id]' order by list"));
            $disTotal = ['bom'=>0,'num'=>0];
            foreach ($all['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $bomArray = $machiningOrderObj->getFactMaterialNum($machiningOrder['id']);
                $bomNum = $machiningOrderObj->getMaterialBom($bomArray, $array['machiningOrderMxId'], $array['materialId']);
                $disTr[] = [
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $bomNum,
                    self::lostZero($array['num'],'numPrecision')
                ];
                $disTotal['bom'] += $bomNum;
                $disTotal['num'] += $array['num'];
            }
            $total_tr = [
                5 => self::lostZero($disTotal['bom'], 'num'),
                6 => self::lostZero($disTotal['num'], 'num'),
            ];
            $data['html'] .= $this->detailList([
                'title' => '材料分配明细',
                'html' => $this->listTable(array('tr' => $disTr, 'showSort' => true, 'total' => $total_tr)),
            ]);

            /*******计件明细********/
            $processTr[] = ['日期','类型', '工序', '产品编码', '产品名称', '规格型号', '计件单位', '产量', '计件单价(' . static::$unit . '）', '计件工资合计(' . static::$unit . '）'];
            $all = find(array(
                'table' => 'process_report',
                'where' => "state = '已确认' and (sendId in (select id from machining_send_order where machiningOrderMxId = '$machiningOrderMx[id]') or sendId in (select id from machining_card_detail where orderId in (select id from machining_card where sourceMxId = '$machiningOrderMx[id]')))"
            ));
            $processTotal = ['yield'=>0,'salary'=>0];
            foreach ($all['array'] as $array) {
                $material = query('material', " id = '$machiningOrderMx[materialId]'");
                $process = query('process', "id = '$array[processId]'");
                $array['yield'] = machiningOrderClass::material_num_change($array['materialId'],$array['unit'],$material['unit'],$array['yield']);
                if ($array['classify'] =='工序报工'){
                    $routingDetail = query('routing_detail', "id = '$array[routingMxId]'");
                    $price = $routingDetail['price'];
                    $salary = self::formattingFigure((float)$routingDetail['price']*$array['yield']);
                }else{
                    //委外报工
                    $array['teamNo'] = date('Y-m-d',strtotime($array['time']));
                    $salary = $array['fee'];
                    $price = $array['yield']>0?self::formattingFigure($array['fee']/$array['yield'],'pricePrecision'):0;
                }

                $processTr[] = [
                    $array['teamNo'],
                    $array['classify'],
                    $process['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    self::lostZero($array['yield'],'numPrecision'),
                    $price,
                    $salary
                ];
                $processTotal['yield'] += $array['yield'];
                $processTotal['salary'] += $salary;
            }
            $total_tr = [
                7 => self::lostZero($processTotal['yield'], 'num'),
                9 => self::formattingFigure($processTotal['salary']),
            ];
            $data['html'] .= $this->detailList([
                'title' => '计件明细',
                'html' => $this->listTable(array('tr' => $processTr, 'showSort' => true, 'total' => $total_tr)),
            ]);

            $costTr[] = ['费用项目', '分摊金额(' . static::$unit . ')'];
            $all = find(array('table' => 'cost_allocation_price', 'where' => "machiningOrderMxId = '$machiningOrderMx[id]'"));
            foreach ($all['array'] as $array) {
                $item = query('cost_allocation_item', "id = '$array[itemId]'");
                $costTr[] = [$item['item'], self::lostZero($array['money'])];
            }
            $total_tr      = [
                1  => self::formattingFigure(array_sum(array_column((array)$all['array'],'money'))),
            ];
            $data['html'] .= $this->detailList([
                'title' => '费用分摊',
                'html' => $this->listTable(array('tr' => $costTr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 工人计件
     */
    public function peopleFee($machiningOrderMxId): float
    {
        $money = 0;
        $all = find(array(
            'table' => "process_report",
            'where' => "(sendId in (select id from machining_send_order where machiningOrderMxId = '$machiningOrderMxId') or sendId in (select id from machining_card_detail where orderId in (select id from machining_card where sourceMxId = '$machiningOrderMxId'))) and state = '已确认'"
        ));
        foreach ($all['array'] as $array) {
            $material = query('material',"id = '$array[materialId]'");
            $array['yield'] = machiningOrderClass::material_num_change($array['materialId'],$array['unit'],$material['unit'],$array['yield']);
            if ($array['classify'] =='工序报工'){
                $routingDetail = query('routing_detail', "id = '$array[routingMxId]'");
                $routing_detail['price'] = $routingDetail['price'] ?: 0;
                $salary = self::formattingFigure((float)$routingDetail['price']*$array['yield']);
            }else{
                //委外报工
                $salary = $array['fee'];
            }
            $money += $salary;
        }
        return self::formattingFigure($money);
    }

    /**
     * 分摊费用
     */
    public function inFee($machiningOrderMxId): array
    {
        $totalNum = 0;//实际产量
        $machiningOrderMx = query('machining_order_mx', "id = '$machiningOrderMxId'");
        $money = find(array('table' => 'cost_allocation_price', 'where' => "machiningOrderMxId = '$machiningOrderMxId'", 'sum' => 'money'));
        $all = find(array(
            'table' => "machining_in_order as a join machining_in_order_detail as b on a.id = b.orderId",
            'field' => "b.materialId,b.num,b.unit,b.id",
            'where' => "b.sourceId = '$machiningOrderMxId' and a.state = '已确认' and a.coid = '" . self::$coid . "' order by b.list asc"
        ));
        foreach ($all['array'] as $array) {
            $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[id]' and coid = '" . self::$coid . "'"));
            foreach ($inventoryAll['array'] as $inventoryDetail) {
                $num = machiningOrderClass::material_num_change($array['materialId'], $inventoryDetail['unit'], $machiningOrderMx['unit'], $inventoryDetail['num']);
                $totalNum += $num;
            }
        }
        return ['money' => $money, 'num' => $totalNum];
    }

    /**
     * 材料耗用
     */
    public function materialFee($machiningOrderMxId): float
    {
        $money = 0;
        $machiningOrderMx = query('machining_order_mx', "id = '$machiningOrderMxId'");
        //领料
        $all = find(array(
            'table' => "pick_order_detail as b join pick_order as a on a.id = b.orderId", 'field' => "b.*,a.recordDate",
            'where' => "a.state = '已确认' and a.type=0 and b.sourceId in (select id from machining_order_detail where orderId = '$machiningOrderMx[orderId]' and targetSkuId = '$machiningOrderMx[id]' and state = '已确认')"
        ));
        foreach ($all['array'] as $array) {
            $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$array[id]' and num >0 and coid = '" . self::$coid . "'"));
            $num = 0;
            foreach ($inventoryAll['array'] as $item) {
                $num += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
            }
            $price = inventoryDefaultClass::getInventoryPrice($array['materialId'], $array['unit'], $array['recordDate']);//库存均价

            //退料数量
            $returnNum = 0;
            $returnAll = find(array(
                'table' => "pick_order as a join pick_order_detail as b on a.id = b.orderId",
                'field' => "b.*",
                'where' => "a.state = '已确认' and a.type=1 and
                 b.sourceId in (select d.id from pick_order as c join pick_order_detail as d on c.id = d.orderId where d.materialId = '$array[materialId]' and c.state = '已确认' and c.type = 0 and d.sourceId in (select id from machining_order_detail where orderId = '$machiningOrderMx[orderId]' and targetSkuId = '$machiningOrderMx[id]' and state = '已确认')) "));
            foreach ($returnAll['array'] as $returnMaterail) {
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$returnMaterail[id]' and num >0 and coid = '" . self::$coid . "'"));
                $returnNum = 0;
                foreach ($inventoryAll['array'] as $item) {
                    $returnNum += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                }
            }
            $num = $num - $returnNum;
            $money += $num * $price;
        }
        //配料
        $all = find(array(
            'table' => 'material_distribute_num as a join material_distribute as b on a.orderId = b.id',
            'field' => "a.*,b.recordDate",
            'where' => "b.state = '已确认' and b.coid = '" . self::$coid . "' and a.machiningOrderMxId = '$machiningOrderMx[id]'"
        ));
        foreach ($all['array'] as $array) {
            $price = inventoryDefaultClass::getInventoryPrice($array['materialId'], $array['unit'], $array['recordDate']);//库存均价
            $money += $array['num'] * $price;
        }

        return self::formattingFigure($money);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "machining_order as a join machining_order_mx as mx on a.id = mx.orderId join product_line as b on a.lineId = b.id join material as c on c.id = mx.materialId",
                    'field' => "a.*,mx.id as mxId,mx.unit,b.workshop,b.name as lineName,c.code,c.name as materialName,c.model",
                    "where" => "mx.id in ('".implode("','", $checkedId)."') order by a.recordDate desc,a.time asc",
                ))['array'];
            }else{
                $sql = static::rGet(self::$stid . self::page . 'Sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $result = $this->inFee($array['mxId']);
                $peopleFee = $this->peopleFee($array['mxId']);
                $materialFee = $this->materialFee($array['mxId']);
                $costTotal = $peopleFee + $materialFee + $result['money'];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '加工单类型'=>$array['type'],
                            '生产线'=>$array['lineName'],
                            '产品编码'=>$array['code'],
                            '产品名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '实际产量'=> self::lostZero($result['num'],'numPrecision'),
                            '材料耗用'=> $materialFee,
                            '工人计件'=>$peopleFee,
                            '分摊费用'=>$result['money'],
                            '成本合计'=>$costTotal,
                            '成本单价'=>$result['num'] > 0 ? self::formattingFigure($costTotal / $result['num']) : 0,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了" . self::title . "表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . "表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'加工单类型',
                    'aliasName'=>'加工单类型',
                ],
                [
                    'columnName'=>'生产线',
                    'aliasName'=>'生产线',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'实际产量',
                    'aliasName'=>'实际产量',
                ],
                [
                    'columnName'=>'材料耗用',
                    'aliasName'=>'材料耗用',
                ],
                [
                    'columnName'=>'工人计件',
                    'aliasName'=>'工人计件',
                ],
                [
                    'columnName'=>'分摊费用',
                    'aliasName'=>'分摊费用',
                ],

                [
                    'columnName'=>'成本合计',
                    'aliasName'=>'成本合计',
                ],
                [
                    'columnName'=>'成本单价',
                    'aliasName'=>'成本单价',
                ],
            ]
        };
    }
}

